package com.example.bicycle.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        
        // 明确指定允许的源
        corsConfiguration.addAllowedOrigin("http://localhost:8082");
        corsConfiguration.addAllowedOrigin("http://127.0.0.1:8082");
        
        // 允许所有请求头
        corsConfiguration.addAllowedHeader("*");
        
        // 允许所有请求方法
        corsConfiguration.addAllowedMethod("*");
        
        // 允许携带认证信息（cookies等）
        corsConfiguration.setAllowCredentials(true);
        
        // 预检请求的缓存时间
        corsConfiguration.setMaxAge(MAX_AGE);
        
        // 对所有接口配置跨域设置
        source.registerCorsConfiguration("/**", corsConfiguration);
        
        return new CorsFilter(source);
    }
}
